 package com.example.sms_listener

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.provider.Telephony
import androidx.annotation.NonNull
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry
import android.util.Log

/**
 * Flutter SMS监听和发送插件主类
 * 
 * 负责处理Flutter与Android原生代码之间的通信
 * 实现短信监听、发送、权限管理等核心功能
 * 支持前台服务的后台监听和两种发送模式
 */
class SmsListenerPlugin: FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.RequestPermissionsResultListener {
    /// Method Channel用于方法调用
    private lateinit var methodChannel: MethodChannel
    
    /// Permission Channel用于权限管理
    private lateinit var permissionChannel: MethodChannel
    
    /// Event Channel用于事件流
    private lateinit var eventChannel: EventChannel
    
    /// 应用上下文
    private var context: Context? = null
    
    /// Activity实例
    private var activity: Activity? = null
    
    /// 权限管理器
    private var permissionManager: PermissionManager? = null
    
    /// 短信发送管理器
    private var smsSendManager: SmsSendManager? = null
    
    /// 事件流处理器
    private var eventStreamHandler: SmsEventStreamHandler? = null
    
    /// 是否正在监听
    private var isListening: Boolean = false

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        methodChannel = MethodChannel(flutterPluginBinding.binaryMessenger, "sms_listener")
        methodChannel.setMethodCallHandler(this)
        
        permissionChannel = MethodChannel(flutterPluginBinding.binaryMessenger, "sms_listener/permissions")
        permissionChannel.setMethodCallHandler(this)
        
        eventChannel = EventChannel(flutterPluginBinding.binaryMessenger, "sms_listener/events")
        eventStreamHandler = SmsEventStreamHandler()
        eventChannel.setStreamHandler(eventStreamHandler)
        
        Log.d("SmsListenerPlugin", "EventStreamHandler已创建: $eventStreamHandler")
        
        // 设置到服务中
        SmsListenerService.eventStreamHandler = eventStreamHandler
        Log.d("SmsListenerPlugin", "EventStreamHandler已设置到服务中")
        
        context = flutterPluginBinding.applicationContext
        permissionManager = PermissionManager()
        smsSendManager = SmsSendManager()
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            // 监听相关方法
            "startListening" -> startListening(result)
            "stopListening" -> stopListening(result)
            "getLastSms" -> getLastSms(result)
            "getSmsHistory" -> getSmsHistory(call, result)
            "configure" -> configure(call, result)
            
            // 发送相关方法
            "sendSmsBackground" -> sendSmsBackground(call, result)
            "sendSmsWithIntent" -> sendSmsWithIntent(call, result)
            "isSmsAvailable" -> isSmsAvailable(result)
            "getDefaultSmsApp" -> getDefaultSmsApp(result)
            
            // 权限相关方法
            "requestSmsPermissions" -> requestSmsPermissions(result)
            "requestSmsSendPermission" -> requestSmsSendPermission(result)
            "requestAllSmsPermissions" -> requestAllSmsPermissions(result)
            "hasSmsPermissions" -> hasSmsPermissions(result)
            "hasSmsSendPermission" -> hasSmsSendPermission(result)
            "hasAllSmsPermissions" -> hasAllSmsPermissions(result)
            "getPermissionStatus" -> getPermissionStatus(call, result)
            "openAppSettings" -> openAppSettings(result)
            
            else -> result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        methodChannel.setMethodCallHandler(null)
        permissionChannel.setMethodCallHandler(null)
        eventChannel.setStreamHandler(null)
        
        // 停止前台服务
        stopForegroundService()
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
        permissionManager?.setActivity(activity)
        binding.addRequestPermissionsResultListener(this)
    }

    override fun onDetachedFromActivityForConfigChanges() {
        activity = null
        permissionManager?.setActivity(null)
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        activity = binding.activity
        permissionManager?.setActivity(activity)
        binding.addRequestPermissionsResultListener(this)
    }

    override fun onDetachedFromActivity() {
        activity = null
        permissionManager?.setActivity(null)
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ): Boolean {
        Log.d("SmsListenerPlugin", "收到权限请求结果: requestCode=$requestCode, permissions=${permissions.contentToString()}, grantResults=${grantResults.contentToString()}")
        permissionManager?.onRequestPermissionsResult(requestCode, permissions, grantResults)
        return true
    }

    /**
     * 开始监听短信
     */
    private fun startListening(result: Result) {
        context?.let { ctx ->
            try {
                if (!isListening) {
                    // 检查权限
                    if (!permissionManager?.hasSmsPermissions(ctx)!!) {
                        result.error("PERMISSION_DENIED", "缺少SMS权限", null)
                        return
                    }
                    
                    // 启动前台服务
                    startForegroundService()
                    
                    isListening = true
                    result.success(true)
                } else {
                    result.error("ALREADY_LISTENING", "短信监听已经在运行", null)
                }
            } catch (e: Exception) {
                result.error("START_LISTENING_ERROR", "启动监听失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }

    /**
     * 停止监听短信
     */
    private fun stopListening(result: Result) {
        context?.let { ctx ->
            try {
                if (isListening) {
                    // 停止前台服务
                    stopForegroundService()
                    
                    isListening = false
                    result.success(true)
                } else {
                    result.success(false)
                }
            } catch (e: Exception) {
                result.error("STOP_LISTENING_ERROR", "停止监听失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }

    /**
     * 启动前台服务
     */
    private fun startForegroundService() {
        context?.let { ctx ->
            try {
                val serviceIntent = Intent(ctx, SmsListenerService::class.java)
                ctx.startForegroundService(serviceIntent)
            } catch (e: Exception) {
                throw RuntimeException("启动前台服务失败: ${e.message}", e)
            }
        }
    }

    /**
     * 停止前台服务
     */
    private fun stopForegroundService() {
        context?.let { ctx ->
            try {
                val serviceIntent = Intent(ctx, SmsListenerService::class.java)
                ctx.stopService(serviceIntent)
            } catch (e: Exception) {
                // 忽略停止服务的异常
            }
        }
    }

    /**
     * 获取最后一条短信
     */
    private fun getLastSms(result: Result) {
        context?.let { ctx ->
            try {
                val smsData = SmsHelper.getLastSms(ctx)
                result.success(smsData)
            } catch (e: Exception) {
                result.error("GET_LAST_SMS_ERROR", "获取短信失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }

    /**
     * 获取短信历史记录
     */
    private fun getSmsHistory(call: MethodCall, result: Result) {
        context?.let { ctx ->
            try {
                val limit = call.argument<Int>("limit") ?: 10
                val offset = call.argument<Int>("offset") ?: 0
                val smsHistory = SmsHelper.getSmsHistory(ctx, limit, offset)
                result.success(smsHistory)
            } catch (e: Exception) {
                result.error("GET_SMS_HISTORY_ERROR", "获取短信历史失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }

    /**
     * 配置监听器
     */
    private fun configure(call: MethodCall, result: Result) {
        context?.let { ctx ->
            try {
                val enableBackground = call.argument<Boolean>("enableBackground") ?: true
                val filterSender = call.argument<List<String>>("filterSender")
                
                // 保存配置到SharedPreferences
                SmsReceiver.saveConfiguration(ctx, enableBackground, filterSender)
                
                result.success(true)
            } catch (e: Exception) {
                result.error("CONFIGURE_ERROR", "配置失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }

    /**
     * 请求SMS权限
     */
    private fun requestSmsPermissions(result: Result) {
        val act = activity
        if (act == null) {
            result.error("ACTIVITY_NULL", "Activity为空", null)
            return
        }
        
        val permMgr = permissionManager
        if (permMgr == null) {
            result.error("PERMISSION_MANAGER_NULL", "PermissionManager为空", null)
            return
        }
        
        permMgr.requestSmsPermissions(act) { granted ->
            result.success(granted)
        }
    }

    /**
     * 检查是否有SMS权限
     */
    private fun hasSmsPermissions(result: Result) {
        context?.let { ctx ->
            val hasPermissions = permissionManager?.hasSmsPermissions(ctx) ?: false
            result.success(hasPermissions)
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }

    /**
     * 获取权限状态
     */
    private fun getPermissionStatus(call: MethodCall, result: Result) {
        context?.let { ctx ->
            try {
                val permission = call.argument<String>("permission")
                if (permission != null) {
                    val status = permissionManager?.getPermissionStatus(ctx, permission)
                    result.success(status)
                } else {
                    result.error("INVALID_ARGUMENT", "权限参数为空", null)
                }
            } catch (e: Exception) {
                result.error("GET_PERMISSION_STATUS_ERROR", "获取权限状态失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }

    /**
     * 打开应用设置
     */
    private fun openAppSettings(result: Result) {
        activity?.let { act ->
            try {
                permissionManager?.openAppSettings(act)
                result.success(true)
            } catch (e: Exception) {
                result.error("OPEN_SETTINGS_ERROR", "打开设置失败: ${e.message}", null)
            }
        } ?: result.error("ACTIVITY_NULL", "Activity为空", null)
    }

    /**
     * 后台发送短信
     */
    private fun sendSmsBackground(call: MethodCall, result: Result) {
        context?.let { ctx ->
            try {
                val phoneNumber = call.argument<String>("phoneNumber")
                val message = call.argument<String>("message")
                
                if (phoneNumber.isNullOrEmpty()) {
                    result.error("INVALID_ARGUMENT", "手机号码不能为空", null)
                    return
                }
                
                if (message.isNullOrEmpty()) {
                    result.error("INVALID_ARGUMENT", "短信内容不能为空", null)
                    return
                }
                
                // 检查发送权限
                if (!permissionManager?.hasSmsSendPermission(ctx)!!) {
                    result.error("PERMISSION_DENIED", "缺少SMS发送权限", null)
                    return
                }
                
                val sendResult = smsSendManager?.sendSmsBackground(ctx, phoneNumber, message) ?: false
                result.success(sendResult)
                
            } catch (e: Exception) {
                result.error("SEND_SMS_ERROR", "发送短信失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }
    
    /**
     * 使用系统Intent发送短信
     */
    private fun sendSmsWithIntent(call: MethodCall, result: Result) {
        context?.let { ctx ->
            try {
                val phoneNumber = call.argument<String>("phoneNumber")
                val message = call.argument<String>("message")
                
                val intentResult = smsSendManager?.sendSmsWithIntent(ctx, phoneNumber, message) ?: false
                result.success(intentResult)
                
            } catch (e: Exception) {
                result.error("SEND_SMS_INTENT_ERROR", "打开系统短信界面失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }
    
    /**
     * 检查短信功能是否可用
     */
    private fun isSmsAvailable(result: Result) {
        context?.let { ctx ->
            try {
                val isAvailable = smsSendManager?.isSmsAvailable(ctx) ?: false
                result.success(isAvailable)
            } catch (e: Exception) {
                result.error("CHECK_SMS_AVAILABLE_ERROR", "检查短信功能可用性失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }
    
    /**
     * 获取默认短信应用
     */
    private fun getDefaultSmsApp(result: Result) {
        context?.let { ctx ->
            try {
                val defaultApp = smsSendManager?.getDefaultSmsApp(ctx)
                result.success(defaultApp)
            } catch (e: Exception) {
                result.error("GET_DEFAULT_SMS_APP_ERROR", "获取默认短信应用失败: ${e.message}", null)
            }
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }

    /**
     * 请求SMS发送权限
     */
    private fun requestSmsSendPermission(result: Result) {
        val act = activity
        if (act == null) {
            result.error("ACTIVITY_NULL", "Activity为空", null)
            return
        }
        
        val permMgr = permissionManager
        if (permMgr == null) {
            result.error("PERMISSION_MANAGER_NULL", "PermissionManager为空", null)
            return
        }
        
        permMgr.requestSmsSendPermission(act) { granted ->
            result.success(granted)
        }
    }
    
    /**
     * 请求所有SMS权限
     */
    private fun requestAllSmsPermissions(result: Result) {
        val act = activity
        if (act == null) {
            result.error("ACTIVITY_NULL", "Activity为空", null)
            return
        }
        
        val permMgr = permissionManager
        if (permMgr == null) {
            result.error("PERMISSION_MANAGER_NULL", "PermissionManager为空", null)
            return
        }
        
        permMgr.requestAllSmsPermissions(act) { granted ->
            result.success(granted)
        }
    }

    /**
     * 检查是否有SMS发送权限
     */
    private fun hasSmsSendPermission(result: Result) {
        context?.let { ctx ->
            val hasPermission = permissionManager?.hasSmsSendPermission(ctx) ?: false
            result.success(hasPermission)
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }
    
    /**
     * 检查是否有所有SMS权限
     */
    private fun hasAllSmsPermissions(result: Result) {
        context?.let { ctx ->
            val hasPermissions = permissionManager?.hasAllSmsPermissions(ctx) ?: false
            result.success(hasPermissions)
        } ?: result.error("CONTEXT_NULL", "Context为空", null)
    }
}